package com.mresources.web.config.filter;

import com.mresources.common.dto.Token;
import com.mresources.web.service.JwtService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.apache.logging.log4j.util.Strings;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.crypto.SecretKey;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


public class JwtAuthorizationFilter extends BasicAuthenticationFilter implements Filter {
    private final JwtService jwtService;

    public JwtAuthorizationFilter(AuthenticationManager authenticationManager, JwtService jwtService) {
        super(authenticationManager);
        this.jwtService = jwtService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        setAuth(request.getSession());
        chain.doFilter(request, response);
    }

    private void setAuth(HttpSession session) {
        Object attribute = session.getAttribute("token");
        if (attribute instanceof Token) {
            Token token = (Token) attribute;
            SecretKey key = Keys.hmacShaKeyFor(jwtService.geSecretKey().getBytes());
            Jws<Claims> claimsJws = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token.getAccess_token());
            Claims body = claimsJws.getBody();
            String username = body.get("username", String.class);
            if (!Strings.isEmpty(username)) {
                List<String> auths = body.get("permissions", ArrayList.class);
                List<GrantedAuthority> authorities = auths.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
                UsernamePasswordAuthenticationToken admin = new UsernamePasswordAuthenticationToken(username, null, authorities);
                SecurityContextHolder
                        .getContext()
                        .setAuthentication(
                                admin
                        );
            }
        }

    }
}
